using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace AuthorizeNET {
	public static class Gateway {
		private static string TestGateway = "https://certification.authorize.net/gateway/transact.dll";
		private static string LiveGateway = "https://secure.authorize.net/gateway/transact.dll";

		public static DecisionResponse SendTransactionRequest(Transaction transaction, bool use_test) {
			string target_url = (use_test ? TestGateway : LiveGateway);
			string request_data = transaction.SerializeRequest();
			string result = String.Empty;

			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(target_url);
			request.Method = "POST";
			request.ContentLength = request_data.Length;
			request.ContentType = "application/x-www-form-urlencoded";

			using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) {
				writer.Write(request_data);
				writer.Flush();
				writer.Close();
			}

			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
				result = reader.ReadToEnd();
				reader.Close();
			}

			DecisionResponse res = new DecisionResponse(result);

			return (res);
		}
	}
}
